package com.admission.listener;

import org.hibernate.HibernateException;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.SaveOrUpdateEventListener;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.admission.util.DateUtils;

/**
 * 在自动为entity添加审计信息的Hibernate EventListener.
 * 
 * 在hibernate执行saveOrUpdate()时,自动为AuditableEntity的子类添加审计信息.
 * 
 */
public class AuditListener implements SaveOrUpdateEventListener {

	private static final long serialVersionUID = -7481545873785342485L;

	// private static Logger logger =
	// LoggerFactory.getLogger(AuditListener.class);

	public void onSaveOrUpdate(SaveOrUpdateEvent event)
			throws HibernateException {
		Object object = event.getObject();

		// 如果对象是AuditableEntity子类,添加审计信息.
		if (object instanceof AuditableEntity) {
			AuditableEntity entity = (AuditableEntity) object;
			String loginerNo = Struts2Utils
					.getSessionAttribute(SpringSecurityUtils
							.getCurrentUserName()) == "anonymousUser" ? "no logined"
					: SpringSecurityUtils.getCurrentUserName();
				entity.setInputTime(DateUtils.now());
				entity.setInputBy(loginerNo);
				entity.setEditTime(DateUtils.now());
		}
	}
}
